package top.kaoshanji.p1ch01a.mapper;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;
import org.junit.Test;
import top.kaoshanji.p1ch01a.model.Country;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

/**
 * 代码清单test-p1ch01a-12页a：测试查询所有的国家编码
 * 运行 testSelectAll 方法
 * @author kaoshanji
 * ^_^
 * create time 2025/4/12 16:05
 */
public class CountryMapperTest {

    // 静态属性...
    private static SqlSessionFactory sqlSessionFactory;

    // 就在静态方法里初始化..属于是类级别，只有一个，对于对象来说，就是共享的
    @BeforeClass
    public static void init() {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testSelectAll() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            List<Country> countryList = sqlSession.selectList("selectAll");
            printCountryList(countryList);
        } finally {
            sqlSession.close();
        }
    }

    private void printCountryList(List<Country> countryList) {
        for (Country country: countryList) {
            System.out.printf("%-4d%4s%4s\n",country.getId(), country.getCountryName(), country.getCountryCode());
        }
    }


}
